﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using System.Xml.Linq;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using System.Collections;

namespace ActivityTracker.Library
{
    public class Actvity
    {
        #region Global

        IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
        IsolatedStorageFileStream isoStream;
        XDocument xdoc;
        Schedules objSchedules = new Schedules();

        #endregion

        #region Methods

        public void CreateFileDirectory()
        {
            try
            {
                if (!isoStore.DirectoryExists("ActivityTracker"))
                    isoStore.CreateDirectory("ActivityTracker");
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in CreateFileDirectory Method In ActivityTracker.Library.Activity.Actvity file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                throw exNew;
            }
        }

        public void SaveDefaultActivities()
        {
            try
            {
                if (!isoStore.FileExists("ActivityTracker/MyActivities.xml"))
                {
                    Uri uri = new Uri("DefaultData/Activities.xml", UriKind.Relative);
                    xdoc = XDocument.Load(uri.ToString());
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/MyActivities.xml", FileMode.Create, isoStore);
                    xdoc.Save(isoStream);
                    isoStream.Close();
                }
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in SaveDefaultActivities Method In ActivityTracker.Library.Activity.Actvity file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                throw exNew;
            }
        }

        public string GetActivityName(string actId)
        {
            string actName = "";
            try
            {
                if (actId != "")
                {
                    if (isoStore.FileExists("ActivityTracker/MyActivities.xml"))
                    {
                        isoStream = new IsolatedStorageFileStream("ActivityTracker/MyActivities.xml", FileMode.Open, isoStore);
                        xdoc = XDocument.Load(isoStream);
                        isoStream.Close();

                        var act = from c in xdoc.Descendants("activity")
                                  where c.Attribute("id").Value == actId
                                  select c;

                        foreach (XElement ele in act)
                        {
                            actName = ele.Element("name").Value;
                        }
                    }
                }
                return actName;
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in GetActivityName Method In ActivityTracker.Library.Activity.Actvity file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                exNew.Data.Add("actId_GetActivityName", actId);
                throw exNew;
            }
        }

        public List<string> GetActivitiesCountOncatId(string catId)
        {
            List<string> actIdList = new List<string>();
            try
            {
                if (isoStore.FileExists("ActivityTracker/MyActivities.xml"))
                {
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/MyActivities.xml", FileMode.Open, isoStore);
                    xdoc = XDocument.Load(isoStream);
                    isoStream.Close();
                    var catelems = from ct in xdoc.Descendants("activity")
                                   select ct;
                    foreach (var acte in catelems)
                    {
                        foreach (var cele in acte.Descendants("categories").Elements())
                        {
                            if (cele.Attribute("catid").Value == catId)
                            {
                                actIdList.Add(acte.Attribute("id").Value.ToString());
                            }

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in GetActivitiesCountOncatId Method In ActivityTracker.Library.Activity.Actvity file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                exNew.Data.Add("catId_GetActivitiesCountOncatId", catId);
                throw exNew;
            }
            return actIdList;
        }

        public void DeleteActivity(string actId)
        {
            try
            {
                UserImage objUserImage = new UserImage();
                if (isoStore.FileExists("ActivityTracker/MyActivities.xml"))
                {
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/MyActivities.xml", FileMode.Open,isoStore);
                    xdoc = XDocument.Load(isoStream);
                    isoStream.Close();
                    var ActToDel =from t in xdoc.Descendants("activity")
                                         where t.Attribute("id").Value == actId
                                         select t;
                    foreach (var acte in ActToDel)
                    {   
                        if (Convert.ToInt32(actId) >= 1000)
                        objUserImage.DeleteImage(acte.Element("image").Value.ToString());
                        ActToDel.Remove();
                        isoStream = new IsolatedStorageFileStream("ActivityTracker/MyActivities.xml", FileMode.Create, isoStore);
                        xdoc.Save(isoStream);
                        isoStream.Close();
                        break;
                    }
                   
                   
                   
                }
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in DeleteActivity Method In ActivityTracker.Library.Activity.Actvity file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                exNew.Data.Add("actId_DeleteActivity", actId);
                throw exNew;
            }
        }

        public string GetActivityImageName(string actId)
        {
            string imageName = "";
            try
            {
                if (isoStore.FileExists("ActivityTracker/MyActivities.xml"))
                {
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/MyActivities.xml", FileMode.Open, isoStore);
                    xdoc = XDocument.Load(isoStream);
                    isoStream.Close();
                    var eleImageName = from c in xdoc.Descendants("activity")
                                       where c.Attribute("id").Value == actId
                                       select c;
                    foreach (XElement actImageName in eleImageName)
                    {
                        imageName = actImageName.Element("image").Value;
                        break;
                    }
                }
                return imageName;
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in GetActivityImageName Method In ActivityTracker.Library.Activity.Actvity file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                exNew.Data.Add("actId_GetActivityImageName", actId);
                throw exNew;
            }
        }

        public List<ActivityProp> LoadActivities(int count)
        {
            List<ActivityProp> objActsList = new List<ActivityProp>();
            try
            {
                UserImage objUserImage = new UserImage();
                int TotalMyAcitivitesCount = 0;
                if (isoStore.FileExists("ActivityTracker/MyActivities.xml"))
                {
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/MyActivities.xml", FileMode.Open, isoStore);
                    xdoc = XDocument.Load(isoStream);
                    isoStream.Close();
                    var ActList = (from t in xdoc.Descendants("activity")
                                   orderby Convert.ToInt32((t.Element("activityViewOrder").Value)) ascending
                                   select t).Take(count);
                    foreach (var Act in ActList)
                    {
                        ActivityProp prop = new ActivityProp();
                        prop.ActName = Act.Element("name").Value;
                        prop.ActImageSrc = objUserImage.LoadActivityImages(Act.Attribute("id").Value.ToString(), Act.Element("image").Value.ToString()) as ImageSource;
                        prop.ActId = Act.Attribute("id").Value;
                        objActsList.Add(prop);
                    }
                    TotalMyAcitivitesCount = (from t in xdoc.Descendants("activity")
                                              orderby Convert.ToInt32((t.Element("activityViewOrder").Value)) ascending
                                              select t).Count();
                    if (objActsList.Count == count && count != TotalMyAcitivitesCount)
                    {
                        ActivityProp objAddGetMore = new ActivityProp();
                        objAddGetMore.ActName = "get more";
                        objAddGetMore.ActImageSrc = null;
                        objAddGetMore.ActIsVisible = Visibility.Collapsed;
                        objActsList.Add(objAddGetMore);
                    }
                }
            }
            catch (Exception ex)
            {
                Exception exNew = new Exception("Exception in LoadActivities Method In ActivityTracker.Library.Activity.Actvity file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
                exNew.Data.Add("count_LoadActivities", count);
                foreach (DictionaryEntry d in ex.Data)
                    exNew.Data.Add(d.Key, d.Value);
                throw exNew;
            }
            return objActsList;
        }

        public XElement GetCategoryElement(ListBox lbxCategories)
        {
            XElement tempcategories = new XElement("categories");
            foreach (CategoryProp itm in lbxCategories.Items)
            {
                tempcategories.Add(new XElement("catName", itm.catName,
                    new XAttribute("catid", itm.CatId)));
            }
               // tempcategories.Add(new XAttribute("catid", itm.CatId), new XElement("catName", itm.catName));
            return tempcategories;
        }

        public void SaveNewActivity(XElement tempcategories, string AcitivtyName, string ImageName, bool LocationTracking)
        {
            try
            {
                if (isoStore.FileExists("ActivityTracker/MyActivities.xml"))
                {
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/MyActivities.xml", FileMode.Open, isoStore);
                    xdoc = XDocument.Load(isoStream);
                    isoStream.Close();
                    int NextId = 1000;
                    var activities = from c in xdoc.Descendants("activity")
                                     orderby (int)c.Attribute("id") descending
                                     select c;
                    foreach (XElement activity in activities)
                    {
                        int ActId = int.Parse(activity.Attribute("id").Value);
                        if (ActId >= 1000)
                        {
                            NextId = ActId + 1;
                        }
                        break;
                    }
                    int NextActitvityViewOrder = 1000;
                    var acts = from c in xdoc.Descendants("activity")
                               orderby (int)c.Element("activityViewOrder") descending
                               select c;
                    foreach (XElement activity in acts)
                    {
                        int ViewOrder = int.Parse(activity.Element("activityViewOrder").Value);
                        if (ViewOrder >= 1000)
                        {
                            NextActitvityViewOrder = ViewOrder + 1;
                        }
                        break;
                    }
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/MyActivities.xml", FileMode.Create, isoStore);
                    xdoc.Root.Add(new XElement("activity", new XAttribute("id", NextId),
                        new XElement(tempcategories),
                        new XElement("name", AcitivtyName),
                        new XElement("image", ImageName),
                        new XElement("favorite", true),
                        new XElement("activityviewcount", 0),
                        new XElement("activityViewOrder", NextActitvityViewOrder),
                        new XElement("locationtracking", LocationTracking)));
                    xdoc.Save(isoStream);
                    isoStream.Close();
                }
            }
            catch (Exception ex)
            {
                Exception exnew = new Exception("Exception in saveImageInLocalStorage Method In ActivityTracker.Library.Activity.Actvity file.\n\n" + ex.Message + "\n\n Stack Trace:- " + ex.StackTrace);
                exnew.Data.Add("AcitivtyName", AcitivtyName);
                exnew.Data.Add("ImageName", ImageName);
                exnew.Data.Add("LocationTracking", LocationTracking);
                throw exnew;
            }
        }

        public void UpdateActivity(string actId, XElement tempcategories, string AcitivtyName, string ImageName, bool LocationTracking)
        {
            try
            {
                if (isoStore.FileExists("ActivityTracker/MyActivities.xml"))
                {
                    isoStream = new IsolatedStorageFileStream("ActivityTracker/MyActivities.xml", FileMode.Open, isoStore);
                    xdoc = XDocument.Load(isoStream);
                    isoStream.Close();
                    var ActList = from t in xdoc.Descendants("activity")
                                  where t.Attribute("id").Value == actId
                                  select t;
                    foreach (XElement eleme in ActList)
                    {
                        eleme.Element("name").Value = AcitivtyName;
                        if (ImageName != "")
                        {
                            eleme.Element("image").Value = ImageName;
                        }
                        eleme.Element("categories").Remove();
                        eleme.Add(new XElement(tempcategories));
                        eleme.Element("locationtracking").Value = LocationTracking.ToString();
                        isoStream = new IsolatedStorageFileStream("ActivityTracker/MyActivities.xml", FileMode.Create, isoStore);
                        xdoc.Save(isoStream);
                        isoStream.Close();
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Exception exnew = new Exception("Exception in saveImageInLocalStorage Method In ActivityTracker.Library.Activity.Actvity file.\n\n" + ex.Message + "\n\n Stack Trace:- " + ex.StackTrace);
                exnew.Data.Add("AcitivtyName", AcitivtyName);
                exnew.Data.Add("ImageName", ImageName);
                exnew.Data.Add("LocationTracking", LocationTracking);
                throw exnew;
            }
        }

        public string DeleteActivityConfirmation(string actId)
        {
            string DeleteConfirmation = "";
            try
            {
                int schedsToDelete = objSchedules.NoOfSchedulesToDelete(actId);
                if (schedsToDelete > 0)
                    DeleteConfirmation = schedsToDelete + " schedules Created for this acitivity.";
                else
                    DeleteConfirmation = "Warning";
            }
            catch (Exception ex)
            {
                Exception exnew = new Exception("Exception in DeleteActivityConfirmation Method In ActivityTracker.Library.Activity.Actvity file.\n\n" + ex.Message + "\n\n Stack Trace:- " + ex.StackTrace);
                exnew.Data.Add("actId_DeleteActivityConfirmation", actId);
                throw exnew;
            }

            return DeleteConfirmation;
        }

        //public void Move(string Selecteditem, string MovetoItem)
        //{
        //    try
        //    {
        //        if (isoStore.FileExists("ActivityTracker/MyActivities.xml"))
        //        {
        //            int selectedvieworder = 0;
        //            int movetovieworder = 0;
        //            isostream = new IsolatedStorageFileStream("ActivityTracker/MyActivities.xml", FileMode.Open, isoStore);
        //            xdoc = XDocument.Load(isostream);
        //            isostream.Close();
        //            XElement selecteditem = (from t in xdoc.Descendants("activity")
        //                                     where t.Attribute("id").Value == Selecteditem
        //                                     select t).Single();
        //            XElement moveditem = (from t in xdoc.Descendants("activity")
        //                                  where t.Attribute("id").Value == MovetoItem
        //                                  select t).Single();
        //            selectedvieworder = Convert.ToInt32(selecteditem.Element("activityViewOrder").Value);
        //            movetovieworder = Convert.ToInt32(moveditem.Element("activityViewOrder").Value);
        //            moveditem.Element("activityViewOrder").Value = selectedvieworder.ToString();
        //            selecteditem.Element("activityViewOrder").Value = movetovieworder.ToString();
        //            isostream = new IsolatedStorageFileStream("ActivityTracker/MyActivities.xml", FileMode.Create, isoStore);
        //            xdoc.Save(isostream);
        //            isostream.Close();
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Exception exNew = new Exception("Exception in Move Method In SaveData file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace);
        //        exNew.Data.Add("Selecteditem", Selecteditem);
        //        exNew.Data.Add("MovetoItem", MovetoItem);
        //        throw exNew;
        //    }
        //}

        #endregion
    }
}
